package com.ccp.dev.system.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.consts.SecretUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.DictionaryService;
import com.ccp.dev.system.service.SysUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@Action(ownermodel = SysAuditModelType.SYSTEM_SETTING)
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_SYSTEM + "/dictionary")
public class DictionaryController extends SysBaseController {
    @Resource
    private DictionaryService dictionaryService;

    /**
     * 跳转到首页
     * @return
     */
    @Action(description="数据字典首页页面跳转",exectype = "页面跳转日志")
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    public String viewList() {
        return "sysDictionary/list";
    }

    /**
     * 跳转新增编辑页面
     * @param request
     * @param modelMap
     * @return
     */
    @Action(description="数据字典新增编辑页面跳转",exectype = "页面跳转日志")
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    public String add(HttpServletRequest request, ModelMap modelMap) {
        //获取父节点ID
        modelMap.put("parentId", RequestUtil.getString(request, "parentId"));
        //获取父节点节点路径
        modelMap.put("nodePath", RequestUtil.getString(request, "parentIdNodePath"));
        //获取分类ID
        modelMap.put("typeId", RequestUtil.getString(request, "typeId"));
        modelMap.put("dicId", RequestUtil.getString(request, "dicId"));
        modelMap.put("isRoot",RequestUtil.getString(request,"isRoot"));
        return "sysDictionary/add";
    }

    /**
     * 根据分类表中nodeKey查询数据字典信息
     * @param request
     * @return
     */
    @Action(description="根据分类表中nodeKey查询数据字典信息",
            detail = "<#assign entity=globalTypeService.getByDictNodeKey(nodeKey)/><#if entity != null>根据分类【${entity.typeName}】</#if>查询数据字典信息<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    public Object list(HttpServletRequest request) {

        SysAuditThreadLocalHolder.putParamerter("success", true);
        String nodeKey = RequestUtil.getString(request, "nodeKey");
        SysAuditThreadLocalHolder.putParamerter("nodeKey", nodeKey);
        try {
            List<Dictionary> dicList = dictionaryService.getDicByNodeKey(nodeKey,true);
            return getResultDataSuccess("operation.success", dicList);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 根据分类表中nodeKey查询树形结构的数据字典信息
     * @param request
     * @return
     */
    @RequestMapping("/treeList")
    @ResponseBody
    @Action(description="根据分类表中nodeKey查询树形结构的数据字典信息",
            detail = "<#assign entity=globalTypeService.getByDictNodeKey(nodeKey)/><#if entity != null>根据分类【${entity.typeName}】</#if>查询数据字典信息<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    public Object treeList(HttpServletRequest request) {
        SysAuditThreadLocalHolder.putParamerter("success", true);
        String nodeKey = RequestUtil.getString(request, "nodeKey");
        SysAuditThreadLocalHolder.putParamerter("nodeKey", nodeKey);
        try {
            Map<String, Object> dataMap = dictionaryService.getTreeDicByNodeKey(nodeKey);
            return getResultDataSuccess("query.success", dataMap);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 保存数据字典信息
     * @param request
     * @param dictionary
     * @return
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存数据字典信息",
            detail = "<#if StringUtil.isEmpty(dicId)>新增<#else>更新</#if>字典【${itemName}】信息<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    public Object save(HttpServletRequest request, @RequestBody Dictionary dictionary) {
        try{
            SysAuditThreadLocalHolder.putParamerter("success", true);
            SysAuditThreadLocalHolder.putParamerter("dicId", dictionary.getDicId());
            SysAuditThreadLocalHolder.putParamerter("itemName", dictionary.getItemName());
            int resultLength = this.dictionaryService.getDicByItemKey(dictionary).size();
            if (resultLength > 0) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return getResultDataError("operation.failure.notnull");
            }
            int resultByItemValue = this.dictionaryService.getDicByItemValue(dictionary).size();
            if(resultByItemValue > 0){
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return getResultDataError("operation.failure.isUnique");
            }
            String id = dictionary.getDicId();
            if (StringUtil.isEmpty(id)) {
                //新增操作
                dictionary.setDicId(UUIDUtils.getUUIDFor32());
                //根节点
                if(Dictionary.ISROOT_YES == dictionary.getIsRoot()){
                    dictionary.setParentId(dictionary.getTypeId());
                    dictionary.setNodePath(dictionary.getTypeId() + "." + dictionary.getDicId() + ".");
                }else{
                    dictionary.setNodePath(dictionary.getNodePath() + dictionary.getDicId() + ".");
                }
                dictionaryService.add(dictionary);
            } else {
                //修改操作
                dictionaryService.update(dictionary);
            }
            return getResultDataSuccess("save.success") ;
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return  getResultDataError("save.failure");
        }
    }

    /**
     * 根据数据字典主键进行删除
     * @param dicId
     * @return
     */
    @Action(description="根据数据字典主键进行删除",
            detail = "根据数据字典主键删除<#if success>【${dicName}】成功<#else>失败</#if>",
            exectype = "删除日志")
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    public Object delete(@RequestParam("id") String dicId) {
        try{
            SysAuditThreadLocalHolder.putParamerter("success", true);
            if (StringUtil.isEmpty(dicId)) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return getResultDataError("delete.failure.message");
            }
            Dictionary dictionary = dictionaryService.getOneById(dicId);
            SysAuditThreadLocalHolder.putParamerter("dicName", dictionary.getItemName());
            dictionaryService.delByDicId(dicId);
            return getResultDataSuccess("delete.success") ;
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return  getResultDataError("delete.failure");
        }
    }

    /**
     * 根据数据字典获取数据字典项信息
     * @param dicId
     * @return
     */
    @Action(description="根据数据字典获取数据字典项信息",
            detail = "根据数据字典获取数据字典项<#if success>【${dicName}】成功<#else>失败</#if>",
            exectype = "查询日志")
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    public Object get(@RequestParam("id") String dicId) {
        try{
            SysAuditThreadLocalHolder.putParamerter("success", true);
            Dictionary dictionary = dictionaryService.getOneById(dicId);
            if (null == dictionary) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return getResultDataError("get.failure");
            }
            SysAuditThreadLocalHolder.putParamerter("dicName", dictionary.getItemName());
            return getResultDataSuccess("get.success", dictionary);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("get.failure");
        }
    }

    /**
     * 根据分类表中nodeKey查询数据字典信息
     * @param request
     * @return
     */
    @Action(description="根据分类表中nodeKey查询数据字典信息",
            detail = "根据分类表中nodeKey查询数据字典信息<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @RequestMapping("/listFilterByUserSecret")
    @ResponseBody
    public Object listFilterByUserSecret(HttpServletRequest request) {
        SysAuditThreadLocalHolder.putParamerter("success", true);
        String nodeKey = RequestUtil.getString(request, "nodeKey");
        SysAuditThreadLocalHolder.putParamerter("nodeKey", nodeKey);
        try {
            List<Dictionary> list = new ArrayList<>();
            List<Dictionary> dicList = dictionaryService.getByNodeKey(nodeKey);
            SysUserService sysUserService = AppUtil.getBean(SysUserService.class);
            //取用户密级，根据用户密级过滤
            String userId = ContextUtil.getCurrentUserId();
            SysUser sysUser = sysUserService.getById(userId);
            int sec = SecretUtil.getUserDataSecretMap().get(sysUser.getPrivacyLevel());
            for(Dictionary dic :dicList){
                if(new Integer(dic.getItemValue())>sec){
                    continue;
                }
                list.add(dic);
            }
            return getResultDataSuccess("operation.success", list);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("query.failure");
        }
    }
}
